﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class ChangeAtlasWindow : EditorWindow 
{
	[MenuItem ("Tools/UIAtlas/Change Atlas")]    
	static void Init () 
	{           
		ChangeAtlasWindow window = (ChangeAtlasWindow)EditorWindow.GetWindow (typeof(ChangeAtlasWindow));   
	}

	static Dictionary<UIAtlas, UIAtlas> changeList = new Dictionary<UIAtlas, UIAtlas>();	//要更换的列表
	static UIAtlas tempSourceAtlas;
	static UIAtlas tempTargetAtlas;
	
	static bool readyToAdd = false;
	void OnGUI () 
	{        
		if(GUILayout.Button("Add a change item"))
		{
			readyToAdd = true;
		}
		
		if(readyToAdd)
		{
			EditorGUILayout.BeginHorizontal();
			{				
				tempSourceAtlas = EditorGUILayout.ObjectField("SourceAtlas", tempSourceAtlas, typeof(UIAtlas), true) as UIAtlas;
				tempTargetAtlas = EditorGUILayout.ObjectField("TargetAtlas", tempTargetAtlas, typeof(UIAtlas), true) as UIAtlas;
				
				if(GUILayout.Button("Add"))			
					AddChange();
			}
			EditorGUILayout.EndHorizontal();
		}
		
		
		if(changeList.Count > 0)
		{
			EditorGUILayout.LabelField("-----------------------更换列表-----------------------");
			foreach(UIAtlas tempSourceAtlas in changeList.Keys)
			{
				EditorGUILayout.BeginHorizontal();
				{
					EditorGUILayout.ObjectField("SourceAtlas", tempSourceAtlas, typeof(UIAtlas), false);
					EditorGUILayout.LabelField("------>");
					EditorGUILayout.ObjectField("TargetAtlas", changeList[tempSourceAtlas], typeof(UIAtlas), false);
				}
				EditorGUILayout.EndHorizontal();
			}
			
			EditorGUILayout.BeginHorizontal();
			{
				if(GUILayout.Button("Change Now"))
					StartChange();
				if(GUILayout.Button("Clean List"))
					changeList.Clear();
			}
			EditorGUILayout.EndHorizontal();
		}
	}
	
	static void AddChange()
	{		
		if(tempSourceAtlas == null || tempTargetAtlas == null)	
		{
			Debug.LogWarning("请选择需要替换的前后图集！");
			return;
		}
		
		changeList.Add(tempSourceAtlas, tempTargetAtlas);
		readyToAdd = false;
	}
	
	static void StartChange()
	{		
		foreach(UIAtlas oldAtlas in changeList.Keys)
		{
			UpdateAtlas(oldAtlas, changeList[oldAtlas]);
		}
	}
	
	/// <summary>
	/// 更新引用者的资源
	/// oldAtlas:原图集
	/// newAtlas:新图集
	/// </summary>
	public static void UpdateAtlas(UIAtlas oldAtlas, UIAtlas newAtlas)
	{
		char[] trimEnd = (".prefab").ToCharArray();
		string spritePath = AssetDatabase.GetAssetPath(oldAtlas).TrimEnd(trimEnd);
		Debug.Log(string.Format("开始同步[{0}]的引用:......", spritePath));
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				UpdateObjDep(file.TrimEnd(trimEnd), gameObj.transform, oldAtlas, newAtlas);
			}
		}
		
		Debug.Log("同步结束！");
	}
		
	/// <summary>
	/// 更新引用者的资源
	/// objPath:引用者路径
	/// trans:引用者
	/// oldAtlas:原图集
	/// newAtlas:新图集
	/// </summary>
	static void UpdateObjDep(string objPath, Transform trans, UIAtlas oldAtlas, UIAtlas newAtlas)
	{
		bool hasDep = false;
		
		UISprite sprite = trans.GetComponent<UISprite>();
		if(sprite != null)
		{
			if(sprite.atlas == oldAtlas)
			{
				sprite.atlas = newAtlas;
				sprite.MakePixelPerfect();
				hasDep = true;
			}
		}
		
//		UIMix mix = trans.GetComponent<UIMix>();
//		if(mix != null)
//		{
//			if(mix.defaultAtlas == oldAtlas)
//			{
//				mix.defaultAtlas = newAtlas;
//				hasDep = true;
//			}
//			
//			for(int i = 0; i < mix.atlasList.Count; i++)
//			{
//				if(mix.atlasList[i] == oldAtlas)
//				{
//					mix.atlasList[i] = newAtlas;
//					hasDep = true;
//				}
//			}
//		}
		
		if(hasDep)
		{
			Debug.Log(string.Format("已同步：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			UpdateObjDep(objPath + "/" + child.name, child, oldAtlas, newAtlas);
		}
	}	
	
	/// <summary>
	/// 更新所有引用者的资源
	/// atlas:引用资源集
	/// oldSpriteName:原图片
	/// newSpriteName:新图片
	/// </summary>
	public static void UpdateDep(UIAtlas atlas, string oldSpriteName, string newSpriteName)
	{
		char[] trimEnd = (".prefab").ToCharArray();
		string spritePath = AssetDatabase.GetAssetPath(atlas).TrimEnd(trimEnd);
		Debug.Log(string.Format("开始同步[{0}]的引用:......", spritePath));
			
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach (string file in files)
        {
			if(Path.GetExtension(file) == ".meta")
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				UpdateObjDep(file.TrimEnd(trimEnd), gameObj.transform, atlas, oldSpriteName, newSpriteName);
			}
		}
		
		Debug.Log("同步结束！");
	}
	
	/// <summary>
	/// 更新引用者的资源
	/// objPath:引用者路径
	/// trans:引用者
	/// atlas:引用资源集
	/// oldSpriteName:原图片
	/// newSpriteName:新图片
	/// </summary>
	static void UpdateObjDep(string objPath, Transform trans, UIAtlas atlas, string oldSpriteName, string newSpriteName)
	{
		bool hasDep = false;
		
		//普通资源
		UISprite sprite = trans.GetComponent<UISprite>();
		if(sprite != null)
		{
			if(sprite.atlas == atlas && sprite.name == oldSpriteName)
			{
				sprite.name = newSpriteName;	
				hasDep = true;
			}
		}
		
		//Mix资源
//		UIMix mix = trans.GetComponent<UIMix>();
//		if(mix != null)
//		{
//			if(mix.defaultAtlas == atlas)
//			{
//				mix.text = mix.text.Replace(":" + oldSpriteName + "}", ":" + newSpriteName + "}");
//				hasDep = true;
//			}
//			
//			for(int i = 0; i < mix.atlasList.Count; i++)
//			{
//				if(mix.atlasList[i] == atlas)	
//				{
//					mix.text = mix.text.Replace(":" + oldSpriteName + "}", ":" + newSpriteName + "}");
//					hasDep = true;
//				}
//			}
//		}
		
		if(hasDep)
		{
			Debug.Log(string.Format("已同步：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			UpdateObjDep(objPath + "/" + child.name, child, atlas, oldSpriteName, newSpriteName);
		}
	} 
	
	[MenuItem ("Tools/UIAtlas/Show Null Atlas")]  
	static void ShowNullAtlas()
	{
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Null Atlas:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckNullAtlas(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测空图集
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckNullAtlas(string objPath, Transform trans)
	{
		bool hasNullFont = false;
		UISprite sprite = trans.GetComponent<UISprite>();
		if(sprite != null)
		{
			if(sprite.atlas == null)
			{
				hasNullFont = true;
			}
		}
		
		if(hasNullFont)
		{
			Debug.Log(string.Format("NULL Atlas：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			CheckNullAtlas(objPath + "/" + child.name, child);
		}
	}
	
	static UIAtlas selectedAtlas;
	[MenuItem ("Tools/UIAtlas/Show Selected Atlas Dep")] 
	static void ShowSelectedAtlasDep()
	{
		if(Selection.activeGameObject != null)
			selectedAtlas = Selection.activeGameObject.GetComponent<UIAtlas>();
		if(selectedAtlas == null)
		{
			Debug.LogError("未选中图集！");
			return;
		}
		
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Atlas Dep:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckSelectedAtlasDep(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测图集引用
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckSelectedAtlasDep(string objPath, Transform trans)
	{
		bool hasSelectedAtlas = false;
		UISprite sprite = trans.GetComponent<UISprite>();
		if(sprite != null)
		{
			if(sprite.atlas == selectedAtlas)
			{
				hasSelectedAtlas = true;
			}
		}
		
		if(hasSelectedAtlas)
		{
			Debug.Log(string.Format("Atlas Dep：{0}", objPath));
		}
		
		//子节点递归
		for(int j = 0; j < trans.childCount; j++)
		{
			Transform child = trans.GetChild(j);
			CheckSelectedAtlasDep(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem ("Tools/UIAtlas/Show Zoomed Normal Sprites")] 
	static void CheckZoomedNormalSprites()
	{
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Zoomed Normal Sprites:......");
		
		string fileFolder = "Assets/GameResources/UI/Dep/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckZoomedNormalSprite(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		Debug.Log("检测完毕！");
	}
	
	/// <summary>
	/// 检测非九宫格图片拉伸
	/// objPath:引用者路径
	/// trans:引用者
	/// </summary>
	static void CheckZoomedNormalSprite(string objPath, Transform trans)
	{
		UISprite sprite = trans.GetComponent<UISprite>();
		if(sprite != null)
		{
			if(!(sprite is UISlicedSprite))
			{
//				if(sprite.size != sprite.spriteSize)
//					Debug.Log(string.Format("Zoomed Normal Sprite：{0}", objPath));
			}
		}
		else
		{		
			//子节点递归
			for(int j = 0; j < trans.childCount; j++)
			{
				Transform child = trans.GetChild(j);
				CheckZoomedNormalSprite(objPath + "/" + child.name, child);
			}
		}
	}
	
	
	static List<string> up1024List = new List<string>();
	static List<string> up512List = new List<string>();
	static List<string> up256List = new List<string>();
	static List<string> down128List = new List<string>();
	[MenuItem("Tools/UIAtlas/Show Large Textures")]
    static void CheckLargeTextures()
    {
		up1024List.Clear();
		up512List.Clear();
		up256List.Clear();
		down128List.Clear();
		
		char[] trimEnd = (".prefab").ToCharArray();
		Debug.Log("开始检测Large Textures:......");
		
		string fileFolder = "Assets/GameResources/UI/Base/Atlas/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				UIAtlas atlas = gameObj.GetComponent<UIAtlas>();
				if(atlas != null)
				{
					Texture uiTexture = atlas.texture;
					if(uiTexture != null)
					{
						int width = uiTexture.width;
						int height = uiTexture.height;
						if(width >= 1024 || height >= 1024)
							up1024List.Add(file);
						else if(width >= 512 || height >= 512)
							up512List.Add(file);
						else if(width >= 256 || height >= 256)
							up256List.Add(file);
						else
							down128List.Add(file);
					}
					else
					{
						Debug.Log(string.Format("窗口{0}缺少资源！", file));
					}
				}
			}
		}
		
		Debug.Log("\n>=1024尺寸的图片集--------------------------------------------------------------");
		foreach(string texture in up1024List)
			Debug.Log(texture);
		
		Debug.Log("\n>=512尺寸的图片集--------------------------------------------------------------");
		foreach(string texture in up512List)
			Debug.Log(texture);
		
		Debug.Log("\n>=256尺寸的图片集--------------------------------------------------------------");
		foreach(string texture in up256List)
			Debug.Log(texture);
		
		Debug.Log("\n<=128尺寸的图片集--------------------------------------------------------------");
		foreach(string texture in down128List)
			Debug.Log(texture);
		
		Debug.Log("检测完毕！");
	}
}
